import type { TableColumnCtx } from 'element-plus';

import type { Dict } from '@croco/framework/types';

import type { DataFormItemProps, DataFormSchema } from '#/components/data-form/types';
import type { FieldProps, OnActionClickFn, RenderScope } from '#/components/data-table';

import { h, reactive } from 'vue';

import { ElText } from 'element-plus';

export function useTable(enums: Record<string, Array<Dict> | undefined>, onActionClick: OnActionClickFn): FieldProps[] {
    const formatter = (row: any, column: TableColumnCtx) => {
        switch (column.property) {
            case 'dept': {
                return row.dept?.name || '--';
            }
            case 'sex':
            case 'status': {
                const dict = enums[column.property]?.find((item) => item.value === row[column.property]);
                return h(ElText, { type: dict?.listClass || 'info' }, { default: () => dict?.label || '--' });
            }
            default: {
                return '';
            }
        }
    };

    return [
        { prop: 'username', label: '用户名', search: true, column: { width: 160, fixed: 'left' } },
        { prop: 'nickname', label: '姓名', search: true, column: { width: 160, fixed: 'left' } },
        { prop: 'dept', label: '所属部门', column: { minWidth: 200, formatter } },
        { prop: 'email', label: '邮箱', column: { minWidth: 250 } },
        { prop: 'mobile', label: '手机号', search: true, column: { width: 150 } },
        { prop: 'sex', label: '性别', column: { width: 100, align: 'center', formatter } },
        { prop: 'status', label: '状态', search: { value: '' }, column: { width: 120, align: 'center', formatter } },
        { prop: 'birthDate', label: '出生日期', column: { width: 120, visible: false } },
        { prop: 'address', label: '家庭住址', column: { width: 350, visible: false } },
        { prop: 'lastLoginIp', label: '最后登录IP地址', column: { width: 150, visible: false } },
        { prop: 'lastLoginTime', label: '最后登录时间', column: { width: 190 } },
        { prop: 'lastLoginLocation', label: '最后登录地址', column: { width: 200, visible: false } },
        { prop: 'createTime', label: '创建时间', column: { width: 190 } },
        { prop: 'modifyBy', label: '修改者', column: { width: 160, visible: false } },
        { prop: 'modifyTime', label: '修改时间', column: { width: 190, visible: false } },
        {
            column: {
                width: 150,
                maxCollapseButtons: 2,
                render: [
                    { auth: 'system:user:edit', onClick: (scope: RenderScope) => onActionClick({ code: 'edit', scope }) },
                    { auth: 'system:user:remove', onClick: (scope: RenderScope) => onActionClick({ code: 'remove', scope }), type: 'danger' },
                    { auth: 'system:user:reset', onClick: (scope: RenderScope) => onActionClick({ code: 'reset', scope }) },
                ],
            },
        },
    ];
}

export function useForm(): DataFormSchema {
    const validateNickname = (rule: any, value: any, callback: any) => {
        if (!rule) {
            return callback();
        }

        if (!value) {
            return callback(new Error('真实姓名不能为空'));
        }

        // 基本长度检查
        if (value.length < 2 || value.length > 6) {
            return callback(new Error('姓名长度应为2-6个汉字'));
        }

        callback();
    };

    const rules = reactive({
        username: [
            { required: true, message: '用户名不能为空', trigger: 'blur' },
            { min: 3, max: 10, message: '用户名长度应为 3-10 个字符', trigger: 'blur' },
            { pattern: /^\w+$/, message: '用户名只能包含字母、数字、下划线', trigger: 'blur' },
        ],
        nickname: [
            { required: true, message: '真实姓名不能为空', trigger: 'blur' },
            { validator: validateNickname, trigger: 'blur' },
        ],
        email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { type: 'email', message: '请输入有效的邮箱地址（如：user@example.com）', trigger: 'blur' },
            { pattern: /^[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i, message: '邮箱格式不正确', trigger: 'blur' },
        ],
        mobile: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { pattern: /^1(3\d|4[014-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: '请输入正确的11位手机号码', trigger: 'blur' },
        ],
    });
    const fields: DataFormItemProps[] = [
        { prop: 'id', primary: true },
        { prop: 'username', label: '用户名' },
        { prop: 'nickname', label: '真实姓名' },
        { prop: 'deptId', label: '所属部门' },
        { prop: 'roles', label: '角色', value: [] },
        { prop: 'email', label: '电子邮箱' },
        { prop: 'mobile', label: '手机号码' },
        { prop: 'sex', label: '性别', value: '2', multiple: false },
        { prop: 'birthDate', label: '出生日期', format: 'YYYY-MM-DD' },
        { prop: 'address', label: '家庭住址' },
        { prop: 'status', label: '状态', value: '0', multiple: false },
    ];
    return { rules, fields };
}
